package com.example.ixform.controllers;



import com.example.ixform.services.IdolService;
import com.example.ixform.entities.Idol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
@RequestMapping("idols")
public class IdolController {

    @Autowired
    IdolService idolService;

    @GetMapping
    public String displayIdols(Model model){

        List<Idol> idols = idolService.getAll();
        model.addAttribute("idols",idols);
        return"idols/list-idols";
    }

    @GetMapping("/new")
    public String displayIdolForm(Model model){

        Idol aIdol = new Idol();
        model.addAttribute("idol",aIdol);
        return "idols/new-idol";
    }

    @PostMapping("/save")
    public String createIdol(Model model, Idol idol, Errors errors){
        if(errors.hasErrors()) return "idols/new-idol";
        //将用户写入的表单存入数据库
        idolService.save(idol);
        //防止重复提交-退回原网页
        return "redirect:/idols";
    }

    @GetMapping("/update")
    public String displayIdolUpdateForm(@RequestParam("id") long theId, Model model){
        Idol theIdol= idolService.findByIdolId(theId);
        model.addAttribute("idol",theIdol);
        return "idols/new-idol";
    }

    @GetMapping("/delete")
    public String deleteIdol(@RequestParam("id") long theId,Model model){
        Idol theIdol = idolService.findByIdolId(theId);
        idolService.delete(theIdol);
        return "idols/new-idol";
    }
}
